import device from '@system.device';
import prompt from '@system.prompt';
import {PAObj, serverName} from '../../common/utils/PAObjClass.js';
import CommonData from '../../common/utils/CommonData.js'
const REQUEST_GET_DEVICE = 1;
const REQUEST_CONNECT = 2;
const REQUEST_SEND_MSG = 3;
const REQUEST_SUBSCRIBE = 4;
const REQUEST_UNSUBSCRIBE = 5;
var myPAObj = new PAObj(serverName.server);

export default {
    data: {
        canvas:{
            width:360,
            height:350,
        },
        ctx:undefined,
        raf:undefined,
        color1:0,
        color2:0,
        t1:1,
        t2:2,
        running:false,
        ball:{
            x:100,
            y:100,
            vx:10,
            vy:3,
            r:20,
            color:"#8A2BE2",//紫色小球
            draw:function(ctx)
            {
                ctx.save();
                ctx.beginPath();
                ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
                ctx.fillStyle=this.color;
                ctx.fill();
                ctx.restore();
            }
        },

        deviceList:[],
        start:false,
        requestId:0,
        isConnect:false,
        isServer:true,//是否是服务端
        isDisappear:false,
        position:0, //在哪一侧，0左侧 1右侧
        overTrigger:false,//超出碰撞检测器
        isPause:false,//是否暂停
        isCurrentPause:false,//是否是当前设备触发的暂停
        isRemote:false,//是否是被启用的
    },
    onInit() {
        console.info("onInit")
    },
    onShow() {
        device.getInfo({
            success:(data)=>{
                this.canvas.width = data.windowWidth/data.screenDensity*2;
                this.canvas.height = data.windowWidth/data.screenDensity;
            }
        })
    },
    onReady() {
        console.info("onReady");
        this.subscribe();
    },
    //页面暂停，此函数运行在onHide之前，onInactive() -> onHide()
    onInactive() {
        console.log('onHide');
        this.pauseGame();
        this.isCurrentPause = true;
        this.sendDataToOther({method:CommonData.JAVACALLBACKFUNC.PauseGame})
        //隐藏时游戏暂停
    },
    //此函数在后台回复到前台的过程中运行在onShow之后前，onShow() -> onActive()
    onActive() {
        //如果在暂停状态则重新激活
    },
//不知道为啥不好用
//    //点击返回按钮，onBackPress() -> onHide() -> onDestroy()
//    onBackPress() {
//        //通知java断开连接,关闭ability
//        return true;
//    },
    onDestroy() {
        this.unsubscribe();
        this.stopGameDraw();
        this.sendDataToOther({method:CommonData.JAVACALLBACKFUNC.Disconnect})
    },
    //pos标识在哪侧 0左侧 1右侧
    onStart(pos) {
        this.position = pos
        this.start = true;
        if(this.isConnect) {
            this.sendDataToOther({method:CommonData.JAVACALLBACKFUNC.StartGame,pos:!pos});
        }
        setTimeout(()=>{
            let getCanvas = this.$refs.ballCanvas;
            this.ctx = getCanvas.getContext("2d");
            this.initCanvas();
        }, 500)
    },

    closeDialog() {
        this.$element('simpledialog').close()
    },

    //获取可连接的设备
    getDeviceListBtnClick() {
        console.log("获取可连接设备");
        myPAObj.callAbility(REQUEST_GET_DEVICE).then(res => {
            res = JSON.parse(res);
            //将设备ID脱敏
            for(let i = 0;i<res.deviceInfo.length;i++) {
                let deviceId = res.deviceInfo[i].deviceId
                res.deviceInfo[i].deviceIdEn = '';
                res.deviceInfo[i].deviceIdEn = deviceId.substring(0,4) + "******" + deviceId.substring(deviceId.length-4);
            }
            this.deviceList = res.deviceInfo;
            this.$element('simpledialog').show()
        })
    },
    //与单个设备连接
    connectDeviceById(deviceId) {
        let data = {
            deviceId:deviceId,
            jsRoute:"pages/ballpageserver/ballpageserver",
        }
        myPAObj.callAbility(REQUEST_CONNECT, data).then(res => {
            console.log(res);
            this.isConnect = true;
            this.$element('simpledialog').close()
        }).catch(e=>{
            this.$element('simpledialog').close()
        })
    },
    //给连接好的那台设备发送信息
    sendDataToOther(data) {

        myPAObj.callAbility(REQUEST_SEND_MSG,data)
    },
    //订阅
    subscribe() {
        let data = {
            posX: '100',
            posY: '200'
        }
        myPAObj.subscribeAbilityEvent(REQUEST_SUBSCRIBE, data, this.subCallBack).then(res => {
            console.log(res);
            res = JSON.parse(res);
        })
    },
    //取消订阅
    unsubscribe: function () {
        myPAObj.unsubscribeAbilityEvent(REQUEST_UNSUBSCRIBE).then(res => {
            console.log(res);
        })
    },
    //订阅的回调函数
    subCallBack(res) {
        res = JSON.parse(res);
        let msg = res.data.msg
        msg = JSON.parse(msg);
        if(msg.method) {
            switch (msg.method) {
                case CommonData.JAVACALLBACKFUNC.OnStart :
                this.onStart(msg.pos);
                this.isLocal = false;
                this.isConnect = true;
                break;
                case CommonData.JAVACALLBACKFUNC.SetBall:
                this.comeBakcScreen(msg.data)
                break;
                case CommonData.JAVACALLBACKFUNC.Disconnect:
                this.clear();
                break;
                case CommonData.JAVACALLBACKFUNC.ConnectFail:
                if(this.isConnect) {
                    this.connectFail();
                }
                break;
                case CommonData.JAVACALLBACKFUNC.PauseGame:
                this.pauseGame();
                break;
                case CommonData.JAVACALLBACKFUNC.StartGame:
                this.startGameDraw();
                break;
                default:
                    break;
            }
        }
    },
    connectFail() {
        prompt.showToast({
            message: '连接失败！',
            duration: 2000,
        });
        this.clear();
    },


    initCanvas() {
        console.log(this.isServer);
        if(!this.isServer) {
            this.isDisappear = true;
        }
        let ctx = this.ctx;
        if(this.position) {
            console.log(this.canvas.width/2);
            ctx.translate(this.canvas.width/2 * -1,0)
        }
        ctx.save();
        ctx.strokeStyle=this.getColor();
        ctx.lineWidth=0;
        ctx.strokeRect(0,0,this.canvas.width,this.canvas.height);
        ctx.restore();
        if(!this.running)//没有小球
        {
            this.raf=setInterval(()=>{
                this.draw();
            },30);
            this.running=true;
        }
    },
    clear() {
        this.start = false;
        this.position = 0;
        this.isConnect = false;
        this.isDisappear = false;
        this.running = false;
        this.isLocal = true;
        this.isPause = false;
        this.isCurrentPause = false;
        this.isRemote = false;
        this.isServer = true;
        this.stopGameDraw();
        prompt.showToast({
            message: '链接被断开！',
            duration: 2000,
        });
    },
//产生颜色
    getColor(){
        this.color1+=(this.t1==1)?2:-2;
        this.color2+=(this.t2==1)?1:-1;
        this.t1*=(this.color1>=255||this.color1<=0)?-1:1;
        this.t2*=(this.color2>=255||this.color2<=0)?-1:1;
        return "rgb("+this.color1+","+this.color2+","+20+")";
    },
    draw() {
        let ctx = this.ctx;
        ctx.save();
        ctx.fillStyle='rgba(255,255,255,0.2)';
        ctx.fillRect(0,0,this.canvas.width,this.canvas.height);
        ctx.restore();

        if(this.isServer) {
            //计算速度
            this.ball.vy *= 0.99;
            this.ball.vy += 2;
            let tempMinWdith = 0;
            let tempMaxWdith = this.canvas.width;

            this.ball.vx*=(this.ball.x+this.ball.r>=tempMaxWdith||this.ball.x-this.ball.r<=tempMinWdith)?-1:1;
            this.ball.vy*=(this.ball.y+this.ball.r>=this.canvas.height||this.ball.y-this.ball.r<=0)?-1:1;


            //计算位置
            this.ball.x+=this.ball.vx;
            this.ball.y+=this.ball.vy;
            //画出图形
            this.ball.color="rgb("+138+","+this.color1+","+226+")";

            let data = {
                x:this.ball.x,
                y:this.ball.y,
                color:this.ball.color
            }
            this.sendDataToOther({method:CommonData.JAVACALLBACKFUNC.SetBall,data:data})
        }
        this.ball.draw(ctx);
    },
    //同步位置
    setBall(ball) {
        this.ball.x = ball.x
        this.ball.y = ball.y
        this.ball.color = ball.color
    },
}
